const http = require('http');
const common = require('./common');
const fs = require('fs');
const uuid = require('uuid/v4');
const zlib = require('zlib');

let server = http.createServer((request, response) => {
	
	let arr = [];

	request.on('data', data => {
		arr.push(data);
	})

	request.on('end', () => {
		let data = Buffer.concat(arr);  // data 是接收的全部数据
		
		let post = {};   // 存普通数据
		let file = {};   // 存文件信息
		if (request.headers['content-type']) {
			let contentType = request.headers['content-type'].split('; ')[1];
			if (contentType) {
				let boundary = `--${contentType.split('=')[1]}`;
				let arr = data.split(boundary);
				arr.shift();
				arr.pop();
				arr = arr.map(item => item.slice(2, item.length - 2));

				arr.forEach(item => {
					let n = item.indexOf('\r\n\r\n');

					let disposition = item.slice(0, n);
					let content = item.slice(n + 4);
					disposition = disposition.toString()

					if (disposition.indexOf('\r\n') == -1) {
						content = content.toString();
						let name = disposition.split('; ')[1].split('=')[1];
						name = name.substring(1, name.length - 1);
						post[name] = content;

					} else {
						let [line1, line2] = disposition.split('\r\n');
						let [, name, filename] = line1.split('; ');
						let type = line2.split(': ')[1];

						name = name.split('=')[1]
						name = name.substring(1, name.length - 1);

						filename = filename.split('=')[1]
						filename = filename.substring(1, filename.length - 1);

						let path = `upload/${uuid().replace(/\-/g,'')}`;

						fs.writeFile(path, content, err => {
							if (err) {
								console.log('错误');
							} else {
								file[name] = [filename, type, path];
								console.log(file);
								console.log('成功');
							}
						})
					}
				});

				
			}

		}
		response.end();
	})

})

server.listen(8080);